package com.xmg.p2p.base.service.impl;

import com.xmg.p2p.base.domain.RealAuth;
import com.xmg.p2p.base.domain.Userinfo;
import com.xmg.p2p.base.mapper.RealAuthMapper;
import com.xmg.p2p.base.query.PageResult;
import com.xmg.p2p.base.query.RealAuthQO;
import com.xmg.p2p.base.service.IRealAuthService;
import com.xmg.p2p.base.service.IUserinfoService;
import com.xmg.p2p.base.util.BitStatesUtils;
import com.xmg.p2p.base.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class RealAuthServiceImpl implements IRealAuthService{
    @Autowired
    private RealAuthMapper realAuthMapper;
    @Autowired
    private IUserinfoService userinfoService;
    @Override
    public RealAuth get(Long realAuthId) {
        return realAuthMapper.selectByPrimaryKey(realAuthId);
    }

    @Override
    public void apply(RealAuth realAuth) {
        Userinfo current = userinfoService.getCurrent();
        if(!current.getIsRealAuth()&&current.getRealAuthId()==null){
            realAuth.setState(RealAuth.STATE_APPLY);
            realAuth.setApplyTime(new Date());
            realAuth.setApplier(UserContext.getCurrent());
            realAuthMapper.insert(realAuth);
            current.setRealAuthId(realAuth.getId());
            userinfoService.update(current);
        }
    }

    @Override
    public PageResult query(RealAuthQO qo) {
        int count = realAuthMapper.queryCount(qo);
        if(count>0){
            return new PageResult(realAuthMapper.query(qo),count,qo.getCurrentPage(),qo.getPageSize());
        }
        return PageResult.empty(qo.getPageSize());
    }

    @Override
    public void audit(Long id, String remark, int state) {
        RealAuth realAuth = get(id);
        if(realAuth!=null&&realAuth.getState()==RealAuth.STATE_APPLY){
            realAuth.setState(state);
            realAuth.setAuditTime(new Date());
            realAuth.setAuditor(UserContext.getCurrent());
            Userinfo applier = userinfoService.get(realAuth.getApplier().getId());
            if(state==RealAuth.STATE_PASS){
                if(!applier.getIsRealAuth()){
                    applier.addState(BitStatesUtils.OP_REAL_AUTH);
                    applier.setRealName(realAuth.getRealName());
                    applier.setIdNumber(realAuth.getIdNumber());
                    applier.setRealAuthId(realAuth.getId());
                }else {
                    applier.setRealAuthId(null);
                }
            }
            realAuthMapper.updateByPrimaryKey(realAuth);
            userinfoService.update(applier);
        }
    }
}
